<template>
  <div class="rectisetting">
    <div class="rectisetting__item">
      <span class="rectisetting__item--label">
        <el-button @click="dialogTimes = true" type="primary"
          >设置发货单生成时间</el-button
        >
      </span>
      <div
        class="rectisetting__item--con rectisetting__item--times"
        v-if="rections.setTime.length && rections.setTime.join('、')"
      >
        每日 {{ rections.setTime.join("、") }} 自动生成发货单
      </div>
    </div>

    <el-form label-width="160px" label-position="left">
      <el-form-item label="预计提货时间" required>
        <div class="rectisetting__item--con rectisetting__item--times">
          发货单生成后
          <el-input-number
            :step="1"
            :min="0"
            step-strictly
            :controls="false"
            class="rectisetting__item--expect"
            v-model="rections.setGetGoodTime"
            size="mini"
          >
          </el-input-number
          >小时
        </div>
      </el-form-item>
      <el-form-item
        :label="`${isPointSet ? '提货点' : '团长'}配送方式`"
        required
      >
        <div class="rectisetting__item--con">
          <div class="rectisetting__item--times">
            <el-checkbox :value="true" disabled>客户自提</el-checkbox>
          </div>
          <div class="rectisetting__item--times">
            <el-checkbox
              @change="shipTypeChange"
              v-model="rections.shippingType"
              >送货上门</el-checkbox
            >
            <el-button
              v-show="rections.shippingType"
              class="rectisetting__item--settime"
              @click="dialogArea = true"
              >{{ rections.goodPointIdsPercentage }}设置投放区域
            </el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item
        label-width="145px"
        style="margin-left: 15px"
        label="配送费限额"
        v-show="rections.shippingType"
      >
        <div class="rectisetting__item--con rectisetting__item--times">
          配送费最高
          <el-input-number
            :min="0"
            :controls="false"
            class="rectisetting__item--expect"
            v-model="rections.shippingPrice"
            @input="shippingKeydown"
            size="mini"
          >
          </el-input-number
          >元
        </div>
      </el-form-item>
    </el-form>

    <el-button class="rectisetting__savebtn" @click="saveData" type="primary"
      >保存
    </el-button>

    <SetInvoiceTime
      :dialogTimes.sync="dialogTimes"
      :invoiceId="rections.id"
      :timeLists.sync="rections.setTime"
    >
    </SetInvoiceTime>

    <PutArea
      ref="refPutArea"
      :dialogType="2"
      :isPointSet="isPointSet"
      :areaList="areaList"
      :autoShippingState.sync="rections.autoShippingState"
      :goodPointIdsPercentage.sync="rections.goodPointIdsPercentage"
      :dialogArea.sync="dialogArea"
      @areaIsReady="areaIsReady"
    >
    </PutArea>
  </div>
</template>

<script lang="ts">
import { Vue, Component, PropSync, Ref } from "vue-property-decorator";
import PutArea from "./PutArea.vue";
import SetInvoiceTime from "./SetInvoiceTime.vue";
import {
  getShipperInfo,
  setShipperManage,
  getShipperLinePointList,
  getShippingPointType,
} from "@/api/rection/index";

@Component({
  components: { PutArea, SetInvoiceTime },
})
export default class RectionSetting extends Vue {
  /** 顶部switch状态 */
  @PropSync("rectStatus", { type: Boolean, default: false })
  syncState: boolean;

  /** refPutArea实例 */
  @Ref("refPutArea")
  refPutArea: any;

  /** 配送设置内容 */
  rections = {
    /** 租户id  */
    tenantId: "",
    /** 城市合伙人id  */
    userId: "",
    state: true,
    // 设置时间,初次获取为[]
    setTime: [],
    // 预计提货时间,初次为""
    setGetGoodTime: "",
    // 是否送货上门: 0=禁用,1=启用
    shippingType: false,
    // 配送价格:最高上限
    shippingPrice: 5,
    // 送货上门区域百分比
    goodPointIdsPercentage: "",
    id: "",
    /** 设置新增提货点是否自动设置送货上门,0false=禁用,1true=启用 */
    autoShippingState: "",
    goodPointIdsString: [],
  };

  /** 设置发货单时间弹框 */
  dialogTimes = false;

  /** 获取区域内提货点 */
  areaList = [];

  /** 设置投放区域 */
  dialogArea = false;

  /** 0-团长 1-提货点 */
  isPointSet = 1;

  /**
   * 描述 更新已选择的送货区域
   */
  areaIsReady(data) {
    this.rections.goodPointIdsPercentage = data.range;
    this.rections.goodPointIdsString = data.ids;
    this.dialogArea = false;
  }

  /**
   * 配送设置-获取配送设置内容
   */
  getShipperInfo() {
    const param = {
      /** 租户id  */
      tenantId: "",
      /** 城市合伙人id  */
      userId: "",
    };
    getShipperInfo(param)
      .then((res) => {
        if (res.code === 200) {
          res.data.setGetGoodTime = Number(res.data.setGetGoodTime);
          this.rections = {
            ...this.rections,
            ...res.data,
          };
          this.syncState = res.data.state;
        }
      })
      .catch((err) => {
        this.$message.error(err.msg || "网络异常，请稍后重试");
      });
  }

  /**
   * 配送设置-设置
   */
  setShipperManage() {
    setShipperManage(this.rections)
      .then((res) => {
        if (res.code === 200) {
          this.rections = {
            ...this.rections,
            ...res.data,
          };
        }
      })
      .catch((err) => {
        this.$message.error(err.msg || "网络异常，请稍后重试");
      });
  }

  /**
   * 配送设置-获取区域内提货点
   */
  getShipperLinePointList() {
    const params = {
      /**  */
      tenantId: "",
      /**  */
      userId: "",
    };
    return new Promise((resolve, enject) => {
      getShipperLinePointList(params)
        .then((res) => {
          if (res.code === 200) {
            this.areaList = this.dealAreaLists(res.data) as any;
            resolve(res.data);
          }
        })
        .catch((err) => {
          this.$message.error(err.msg || "网络异常，请稍后重试");
          enject();
        });
    });
  }

  /** 处理areaList */
  dealAreaLists(list = []) {
    const temp = list.filter((i) => i.lists && i.lists.length);
    const ids = [];
    temp.forEach((e) => {
      e.id = e.lineId;
      e.list = e.lists;
      e.name = e.lineName;
      e.list.forEach((i) => {
        i.id = i.communityId;
        i.list = i.lists;
        i.name = i.communityName;
        i.list.forEach((c) => {
          c.id = c.pointId;
          c.name = c.pointName;
          c.isChosen = c.isChoice;
          c.isChosen && ids.push(c.id);
        });
      });
    });
    this.rections.goodPointIdsString = ids.map((i) => {
      return i.toString();
    });
    return temp;
  }

  /**
   * 保存
   */
  saveData() {
    const params = JSON.parse(JSON.stringify(this.rections));
    params.state = this.syncState;
    params.goodPointIdsString = params.goodPointIdsString.map((i) => {
      return i.toString();
    });
    if (!this.saveCheck(params)) {
      return false;
    }
    setShipperManage(params)
      .then((res) => {
        if (res.code === 200) {
          this.$message.success("保存成功");
        }
      })
      .catch((err) => {
        this.$message.error(err.msg || "网络异常，请稍后重试");
      });
  }

  /**
   * 保存检测是否输入完成
   */
  saveCheck(param) {
    if (param.setGetGoodTime === "") {
      this.$message.warning("预计提货时间不能为空");
      return false;
    }
    if (Number(param.setGetGoodTime) < 1) {
      this.$message.warning("预计提货时间填写不合法");
      return false;
    }
    if (!param.setTime.length) {
      this.$message.warning("请设置发货单生成时间");
      return false;
    }
    return true;
  }

  /**
   * 设置最高配送费 input
   */
  shippingKeydown(e) {
    if (+e < 0) {
      this.rections.shippingPrice = 0;
    } else {
      this.rections.shippingPrice = +e;
    }
  }

  /**
   * 配送方式状态改变
   */
  shipTypeChange(v) {
    if (v) {
      this.refPutArea.areaCheckAll.checkAll = true;
      this.refPutArea.areaCheckAll.isIndeterminate = false;
      this.refPutArea.handleCheckAllChange(3);
      this.refPutArea.areasIsReady();
    }
  }

  /**
   * 检测是团长还是提货点
   */
  getShippingPointType() {
    getShippingPointType({})
      .then((res) => {
        if (res.code === 200) {
          this.isPointSet = res.data;
        }
      })
      .catch((err) => {
        this.$message.error(err.msg || "网络异常，请稍后重试");
      });
  }

  mounted() {
    this.getShipperInfo();
    this.getShipperLinePointList();
    this.getShippingPointType();
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/logistics/rection.scss";
.rectisetting__item--settime {
  color: rgb(42, 131, 254);
  border-color: rgb(42, 131, 254);

  &:hover {
    color: rgb(42, 131, 254);
    border-color: rgb(42, 131, 254);
    background-color: #fff;
  }
}
</style>
